const util = require("../../../../utils/util.js");
const db = wx.cloud.database()
const product = db.collection('coupon_info')
const _ = db.command
const dataPageNum = 6
Page({
  data: {
    color: getApp().ext.color,
    show_type: 0,
    orderType: 0, // 0："desc"降序   1："asc"升序
    orderBy: 'createtime',
    selectIndex: 0,
    search_text: '',
    coupon_menu: [],
    coupon_menu_b: [],
    is_all: 0,
    page: 1,
    dataNum: 0,
    isSearch: 0,
    loadCount: 0,
    showCount: 0
  },
  onLoad: function (options) {
    console.log(123)
    this.setData({
      loadCount: this.data.loadCount + 1
    })
    if (options.text) {
      this.setData({
        search_text: options.text
      })
    }
  },
  onShow: function () {
    console.log(345)
    this.setData({
      showCount: this.data.showCount + 1
    })
    if (this.data.showCount == this.data.loadCount) {
      this._clear();
      this.setData({
        dataNum: 0
      })
      this.getProducts(0);
    }
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.req == 1) {
      this._clear();
      this.setData({
        dataNum: 0
      })
      this.getProducts(0);
      this.setData({
        req: 0
      })
    }
  },
  _clear() {
    this.setData({
      page: 1,
      coupon_menu: [],
      is_all: 0,
      show_type: 0,
      orderType: 0,
      orderBy: ''
    })
  },
  getProducts(e) {
    let coupon_menu = this.data.coupon_menu;
    if ("" == this.data.search_text) {
      if (this.data.isSearch == 1)
        this.setData({
          dataNum: 0
        })
      if (e == 3) {
        this.setData({
          dataNum: 0
        })
      }
      db.collection('coupon_info').where({
        state:1, //开启状态
        diyId:wx.getStorageSync('diyId')
      }).orderBy("createtime", "desc").skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
        console.log(res.data);
        console.log(234)
        this.data.page++;
        const DATA = res.data;
        coupon_menu = coupon_menu.concat(DATA);
        this.setData({
          dataNum: this.data.dataNum + dataPageNum
        })
        if (coupon_menu.length != this.data.dataNum) this.data.is_all = 1;

        let tmpCou = [];
        for (var i = 0; i < coupon_menu.length; i++) {
          if (coupon_menu[i].endtime > new Date().getTime()) {  //说明没有过期了
            tmpCou.push(coupon_menu[i])
          }
        }
        this.setData({
          page: this.data.page,
          is_all: this.data.is_all,
          coupon_menu: tmpCou,
          orderType: this.data.orderType,
          coupon_menu_b: tmpCou
        });
      })
      this.setData({
        isSearch: 0
      })
    } else {
      if (this.data.isSearch == 0) {
        this.setData({
          dataNum: 0
        })
      } else {
        if (e != 2) {
          this.setData({
            dataNum: 0
          })
        }
      }
      if (e == 3) {
        this.setData({
          dataNum: 0
        })
      }
      // db.collection('coupon_info').orderBy("createtime",'desc').skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
      //   console.log(res);
      const DATA = this.data.coupon_menu_b;
      console.log(DATA)
      let mData = [];
      var reg = new RegExp(this.data.search_text);
      for (var i = 0; i < DATA.length; i++) {
        if (DATA[i].yhqname.match(reg)) {
          mData.push(DATA[i])
        }
      }
      this.setData({
        page: this.data.page,
        is_all: this.data.is_all,
        coupon_menu: mData,
        orderType: this.data.orderType
      });

      this.setData({
        isSearch: 1
      })
    }
  },
  onPullDownRefresh: function () {
    setTimeout(() => {
      this._clear();
      this.getProducts(1);
      wx.stopPullDownRefresh();
    }, 500)
  },
  onReachBottom: function () {
    if (!this.data.is_all) {
      this.getProducts(2);
    }
  },
  onAddProduct: function (e) {
    wx.navigateTo({
      url: `/pages/manage/coupon-add/index`
    });
  },
  onDelPro(e) {
    console.log(e.currentTarget.dataset.id);
    wx.cloud.callFunction({
      // 云函数名称
      name: 'coupon-del',
      // 传给云函数的参数
      data: {
        id: e.currentTarget.dataset.id
      },
      complete: res => {
        if (res.errMsg == "cloud.callFunction:ok") {
          wx.showToast({
            title: '数据已被删除',
          })
          this._clear();
          this.setData({
            dataNum: 0
          })
          this.getProducts(0);

        } else
          wx.showToast({
            title: '删除失败，请稍后再试',
            icon: 'none'
          })
        console.log('callFunction test result: ', res)
      }
    })
  },
  onUptPro(e) {
    console.log(e.currentTarget.dataset.id);
    wx.navigateTo({
      url: `/pages/manage/coupon-add/index?id=` + e.currentTarget.dataset.id
    });
  },
  bindconfirm(e) {
    console.log(e)
    if (e.detail == null || e.detail == "") {
      this.setData({
        coupon_menu: this.data.coupon_menu_b
      })
      console.log(this.data.coupon_menu_b)
      return;
    }
    this.data.search_text = e.detail;
    // this._clear();
    this.getProducts(0);
  },
  // 领取优惠券
  getCoupon(e) {
    db.collection('coupon_info').where({
      _id: e.currentTarget.dataset.id
    }).get({
      success(ci) {
        console.log(ci.data)
        if (ci.data.length > 0) {
          console.log(ci.data)
          console.log(123132)
          wx.cloud.callFunction({
            // 云函数名称
            name: 'coupon-add',
            // 传给云函数的参数
            data: {
              t: 2,
              id: e.currentTarget.dataset.id,
              diyId:wx.getStorageSync('diyId'),
              openid: wx.getStorageSync('openid'),
              yhqname: ci.data[0].yhqname,
              num: ci.data[0].num,
              limit_num: ci.data[0].limit_num,
              condition: ci.data[0].condition,
              price: ci.data[0].price,
              starttime: ci.data[0].starttime,
              starttimet: ci.data[0].starttimet,
              endtime: ci.data[0].endtime,
              endtimet: ci.data[0].endtimet,
              createtime: util.formatTime(new Date())
            },
            complete: res => {
              console.log('callFunction test result: ', res)
              if (res.errMsg == "cloud.callFunction:ok") {
                if (res.result.code == 201) {
                  wx.showToast({
                    title: res.result.message
                  });
                } else if (res.result.code == 202) {
                  wx.showToast({
                    title: res.result.message
                  });
                } else {
                  wx.showToast({
                    title: "领取成功"
                  });
                }
              } else {
                wx.showToast({
                  title: "暂时不允许领取"
                });
              }
            }
          })
        }
      }
    })
  }
    // wx.doodoo.fetch(`/shop/api/shop/coupon/grtCoupon?id=${e.currentTarget.dataset.item.id}`).then(res => {
    //   if (res && res.data.errmsg == 'ok') {
    //     wx.showToast({
    //       title: "领取成功"
    //     });
    //   } else {
    //     wx.showModal({
    //       title: "提示",
    //       content: res.data.errmsg,
    //       showCancel: false
    //     });
    //   }
    // });
})